'use strict';
//我的券码
import React,{Component} from 'react';
import Header from '../../common/header';
import * as URLconstant from '../../constant/URLconstant'
import Util from '../../common/util';
import Modal from 'react-native-modalbox';
import {
    View,
    Text,
    TouchableOpacity,
    Image,
    StyleSheet,
    ScrollView, ListView
} from 'react-native';
export default class myVoucher extends Component{
    // 构造
      constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            dataSource2: new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2}),
            dataSource: [],
            page:1,
            limit:10,
            isOver:false,
            status:0,
            loaded:true,
            titleHeader:[{ "title": "全部", "status": '0' }, { "title": "待使用", "status": '1' }, { "title": "已使用", "status": '2' }, { "title": "已过期", "status": '3' }],
            isOpen:false,
            code_url:null
        };
        this.onEndReached=this.onEndReached.bind(this)
          this._renderRow=this._renderRow.bind(this)
          this.renderFooter=this.renderFooter.bind(this)
      }

    componentDidMount() {
        this.getVoucher()
    }

      getVoucher(){
          let url = URLconstant.MY_VOUCHER
          let datakey=[]
          datakey['user_id']=this.props.user_id
          datakey['page']=this.state.page
          datakey['limit'] = this.state.limit
          datakey['status'] = this.state.status
          if(this.props.order_id){
              datakey['order_id']=this.props.order_id
          }
          Util.get(url,datakey,this.getVoucherSuc.bind(this),this.errorCallback.bind(this))
      }
    getVoucherSuc(datas){
        if(datas.status==0){
            let isOver = false
            let newDatas
            if(datas.data.length==0){
                newDatas=[]
            }else{
                newDatas = datas.data.list;
            }

            let oldDatas = this.state.dataSource;
            let limit = this.state.limit
            if(newDatas.length<limit){
                isOver=true
            }
            Array.prototype.push.apply(oldDatas, newDatas);
            this.setState({
                isOver:isOver,
                dataSource2: this.state.dataSource2.cloneWithRows(oldDatas),
                dataSource: oldDatas,
                loaded:false,
                page:this.state.page+1
            })
        }
    }
    errorCallback(err){

    }

    onEndReached(){
        let isOver = this.state.isOver
        if(!isOver){
            this.getVoucher()
        }
    }

    returnCouponBg(status){
        if(status==1){
            return(
                <Image
                    source={require('../../imgs/coupon_bg.png')}
                    style={{width:Util.size.width-20,height:(Util.size.width-20)*0.31}}
                    resizeMode={'cover'}
                />
            )
        }else if(status==2){
            return(
                <Image
                    source={require('../../imgs/cp_used.png')}
                    style={{width:Util.size.width-20,height:(Util.size.width-20)*0.31}}
                    resizeMode={'cover'}
                />
            )
        }else{
            return(
                <Image
                    source={require('../../imgs/cp_timer.png')}
                    style={{width:Util.size.width-20,height:(Util.size.width-20)*0.31}}
                    resizeMode={'cover'}
                />
            )
        }
    }

    _renderRow(item){
        return(
            <View key={item.id} style={styles.vouche_item}>
                {this.returnCouponBg(item.use_state)}
                {
                    item.use_state==1?
                        <TouchableOpacity onPress={()=>this.showCode(item.code_url)} style={styles.vouche_view}>
                            <View style={styles.vouche_left}>
                                <Text style={{fontSize:16,color:"#fff",backgroundColor:"transparent"}}>服务兑换券码</Text>
                                <Text style={{fontSize:12,color:"#fff",backgroundColor:"transparent"}}>凭券码可前往附近门店兑换享受对应的服务</Text>
                                <View style={styles.vouche_box}>
                                    <Text style={{color:"#fff",backgroundColor:"transparent"}}>券码:{item.vouche_sn}</Text>
                                </View>
                                <Text style={{color:"#fff",backgroundColor:"transparent"}}>有效期至{item.end}</Text>
                            </View>
                        </TouchableOpacity>
                        :
                        <View style={styles.vouche_view}>
                            <View style={styles.vouche_left}>
                                <Text style={{fontSize:16,color:"#fff",backgroundColor:"transparent"}}>服务兑换券码</Text>
                                <Text style={{fontSize:12,color:"#fff",backgroundColor:"transparent"}}>凭券码可享受对应的服务</Text>
                                <View style={styles.vouche_box}>
                                    <Text style={{color:"#fff",backgroundColor:"transparent"}}>券码:{item.vouche_sn}</Text>
                                </View>
                                <Text style={{color:"#fff",backgroundColor:"transparent"}}>有效期至{item.end}</Text>
                            </View>
                        </View>
                }

            </View>
        )
    }

    showCode(code_url){
        this.setState({
            isOpen:true,
            code_url:code_url
        })
    }

    renderFooter(){
        return (
            <View style={{height:30,alignItems:'center',justifyContent:'center'}}>
                <Text style={{fontSize:12,color:"#969696"}}>{this.state.isOver?"没有更多数据了":"正在加载中"}</Text>
            </View>
        )
    }

    async selectStatus(status){
         await this.setState({
              page:1,
              isOver:false,
              dataSource:[],
              status:status,
             loaded:true
          })
        this.getVoucher()
    }

    showCodeImg(){
          let code_url = this.state.code_url
        if(code_url==null){
              return false
        }
          return(
              <Modal
                  isOpen={this.state.isOpen}
                  backdropPressToClose={false} swipeToClose={false}
                  style={styles.code_modal}>
                    <Image
                        source={{uri:code_url}}
                        style={{width:250,height:250,marginBottom:20}}
                        resizeMode={'cover'}
                    />
                  <TouchableOpacity style={styles.close_btn} onPress={()=>this.setState({
                      isOpen:false
                  })}>
                      <Image
                          source={require('../../imgs/close.png')}
                          resizeMode={'cover'}
                          style={{width:20,height:20}}
                      />
                  </TouchableOpacity>
                  <Text style={{fontSize:16,color:"#000",marginBottom:10}}>券码说明:</Text>
                  <Text style={{fontSize:14,}}>券码说明（按服务下单发放）：凭券码可前往附近门店兑换享受对应的服务：</Text>
              </Modal>
          )
    }

      render(){
          return(
              <View style={{flex:1,backgroundColor:"#f0f0f0"}}>
                  <Header navigator={this.props.navigator} initObj={{ title: '我的券码',id:2}}/>
                  <View style={styles.voucher_header}>
                      {
                          this.state.titleHeader.map((item,index)=>{
                              return(
                                  <TouchableOpacity onPress={()=>this.selectStatus(item.status)} style={styles.header_item} key={index}>
                                      <Text style={item.status==this.state.status?{fontSize:14,color:"#f00"}:{fontSize:14,color:"#333"}}>{item.title}</Text>
                                  </TouchableOpacity>
                              )
                          })
                      }
                  </View>
                  {
                      this.state.loaded?
                          <View style={{flex:1}}>
                              {Util.loading()}
                          </View>
                          :
                            <View style={{flex:1}}>
                                {
                                    this.state.dataSource.length==0?
                                        <View style={{flex:1,alignItems:'center',justifyContent:'center'}}>
                                            <Text>没有服务券码</Text>
                                        </View>:
                                        <ListView
                                            dataSource={this.state.dataSource2}
                                            onEndReached={this.onEndReached}
                                            renderRow={this._renderRow}
                                            renderFooter={this.renderFooter}
                                            style={{paddingHorizontal:10}}
                                        />
                                }
                            </View>
                  }
                  {this.showCodeImg()}
              </View>
          )
      }
}
var styles = StyleSheet.create({
    voucher_header:{
        flexDirection:'row',
        backgroundColor:"#fff"
    },
    header_item:{
        height:40,
        flex:1,
        alignItems:'center',
        justifyContent:'center'
    },
    vouche_item:{
        marginTop:10,
        width:Util.size.width-20,
        height:(Util.size.width-20)*0.31
    },
    vouche_view:{
        position:'absolute',
        top:0,
        left:0,
        width:Util.size.width-20,
        height:(Util.size.width-20)*0.31
    },
    vouche_left:{
        paddingLeft:10,
        paddingTop:5,
        height:(Util.size.width-20)*0.31,
        justifyContent:'space-around'
    },
    vouche_box:{
        height:25,
        borderRadius:12.5,
        paddingHorizontal:10,
        borderWidth:1,
        borderColor:"#000",
        justifyContent:"center",
        width:200,
        marginVertical:5
    },
    code_modal:{
        width:300,
        height:400,
        backgroundColor:"#fff",
        borderRadius:10,
        paddingHorizontal:20,
        paddingVertical:20
    },
    close_btn:{
        position:'absolute',
        top:5,
        right:5,
    }
})